// Copyright (c) 2023 Presto Labs Pte. Ltd.
// Author: tianqiang

#include "coin2/exchange/bit/api_order/native_private_client.h"

#define CHECK_API_LIMIT(action_type, ep)                                                  \
  const static std::string endpoint(ep);                                                  \
  auto ts = GetCurrentTimestamp();                                                        \
  if (!local_rate_tracker_->HasEnoughRateLimit(ts, action_type, endpoint)) {              \
    if (order_logger_cb_) {                                                               \
      rate_tracker_->WriteRateLimitReportMessage(order_logger_cb_);                       \
    }                                                                                     \
    LOG_EVERY_N(WARNING, 50) << "Hit rate limit or api temporary disabled, " << __func__; \
    api_block_info_[__func__]++;                                                          \
    return {};                                                                            \
  }                                                                                       \
  local_rate_tracker_->Push(1, ts, action_type, endpoint);                                \
  api_req_info_[__func__]++;

namespace coin2::exchange::bit::api_order {

BitNativePrivateClient::BitNativePrivateClient(
    const MarketExchangeApi& mea,
    const NativeClientConfig& config_override) {
  mea_ = mea;
  NativeClientConfig config;
  config.set_rest_host("api.bit.com");
  config.set_rest_host_port(443);
  config.MergeFrom(config_override);
  LOG(INFO) << "[BitNativePrivateClient] config: " << config.DebugString();

  auths_.Construct<BitRestAuth, NativeClientConfig>(config);

  rate_tracker_ = std::make_unique<BitRateTracker>(mea_, config);
  local_rate_tracker_ = dynamic_cast<BitRateTracker*>(rate_tracker_.get());
  start_time_ = GetCurrentTimestamp();
}

std::shared_ptr<AsioHttpContext> BitNativePrivateClient::QueryAccountBalance() {
  CHECK_API_LIMIT(ActionType::QUERY, "/um/v1/accounts");

  UrlParamsBuilder builder;
  auto* context = GetAuth()->CreateRequestByGetWithSignature(endpoint, &builder);

  context->query_type = OrderSubTopicId::REST_ACCOUNT_BALANCE;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BitNativePrivateClient::QueryOpenOrders() {
  CHECK_API_LIMIT(ActionType::QUERY, "/spot/v1/open_orders");

  UrlParamsBuilder builder;
  auto* context = GetAuth()->CreateRequestByGetWithSignature(endpoint, &builder);

  context->query_type = OrderSubTopicId::REST_OPEN_ORDERS;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BitNativePrivateClient::QueryHistoryOrders() {
  CHECK_API_LIMIT(ActionType::QUERY, "/spot/v1/orders");

  UrlParamsBuilder builder;
  builder.PutGet("limit", 500);
  auto* context = GetAuth()->CreateRequestByGetWithSignature(endpoint, &builder);

  context->query_type = OrderSubTopicId::REST_DONE_ORDERS;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BitNativePrivateClient::QueryFills() {
  CHECK_API_LIMIT(ActionType::QUERY, "/spot/v1/user/trades");

  UrlParamsBuilder builder;
  builder.PutGet("count", 1000);
  auto* context = GetAuth()->CreateRequestByGetWithSignature(endpoint, &builder);

  context->query_type = OrderSubTopicId::REST_FILL_ORDERS;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BitNativePrivateClient::GenListenKey() {
  if (!listen_key_.empty()) {
    return nullptr;
  }

  UrlParamsBuilder builder;
  auto* context = GetAuth()->CreateRequestByGetWithSignature("/spot/v1/ws/auth", &builder);

  context->query_type = OrderSubTopicId::LISTEN_KEY;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

void BitNativePrivateClient::Prepare() {
  mb_->Subscribe("bit/enable_time", [this](const std::string&, void* data) {
    int64_t value = reinterpret_cast<int64_t>(data);
    local_rate_tracker_->UpdateEnableTime(value);
    LOG(WARNING) << "Bit native client enable_time: " << value;
  });

  mb_->Subscribe("bit/listen_key", [this](const std::string& channel, void* data) {
    listen_key_ = *static_cast<std::string*>(data);

    LOG(INFO) << "BitNativePrivateClient set listen key: " << channel << ", " << listen_key_;
  });
}

std::string BitNativePrivateClient::DebugString() const {
  double delta_t = (GetCurrentTimestamp() - start_time_) / 1.0e9;
  std::stringstream ss;
  ss << "BitNativePrivateClient::DebugString\n";
  ss << "api info\n";
  for (auto& [name, value] : api_req_info_) {
    int32_t blocked = 0;
    if (api_block_info_.count(name) > 0) {
      blocked = api_block_info_.at(name);
    }
    int32_t total_req = value + blocked;
    ss << name << " (total:" << total_req << ", succeeded: " << value << ", blocked: " << blocked
       << ", req_rate: " << value / delta_t << ", block_rate: " << blocked / delta_t << ")\n";
  }
  return ss.str();
}

auto BitNativePrivateClient::GetRestOrderParams(const OrderSpec& order_spec, int64_t proc_order_id)
    -> RestParams {
  auto params = RestParams();
  BitProduct product = BitProduct::FromStr(order_spec.product, order_spec.order_created_time);
  auto product_holder = GetProductHolder(product, order_spec.order_created_time);
  params.set_pair(order_spec.product);
  params.set_label(std::to_string(proc_order_id));

  if (order_spec.order_side == OrderSide::BUY_ORDER) {
    params.set_side("buy");
  } else if (order_spec.order_side == OrderSide::SELL_ORDER) {
    params.set_side("sell");
  } else {
    NOTREACHED() << "Unknown order side: " << static_cast<int>(order_spec.order_side);
  }

  params.set_post_only(order_spec.post_only);

  if (order_spec.order_type == OrderType::MARKET_ORDER) {
    params.set_order_type("market");
    params.set_time_in_force("ioc");
  } else if (order_spec.order_type == OrderType::LIMIT_ORDER) {
    params.set_order_type("limit");
    if (order_spec.duration == coin::proto::OrderDuration::IOC_ORDER) {
      params.set_time_in_force("ioc");
    } else if (order_spec.duration == coin::proto::OrderDuration::FOK_ORDER) {
      params.set_time_in_force("fok");
    } else {
      params.set_time_in_force("gtc");
    }
  } else {
    NOTREACHED() << "Unknown order type: " << static_cast<int>(order_spec.order_type);
  }

  if (order_spec.order_type == OrderType::MARKET_ORDER) {
    NOTREACHED() << "Unsupport market order!";
  }

  auto formatter = product_holder->product_info().order_formatter();
  params.set_qty(formatter.FormatQty(order_spec.qty));
  params.set_price(formatter.FormatPrice(order_spec.price));

  return params;
}

auto BitNativePrivateClient::GetRestCancelParams(const IOrderContext& order_context) -> RestParams {
  auto params = RestParams();

  if (order_context.has_exchange_order_id()) {
    params.set_order_id(order_context.exchange_order_id());
  } else {
    params.set_label(std::to_string(order_context.proc_order_id()));
  }

  return params;
}

std::shared_ptr<AsioHttpContext> BitNativePrivateClient::PlaceOrder(const RestParams& params) {
  CHECK_API_LIMIT(ActionType::PLACE, "/spot/v1/orders");

  UrlParamsBuilder builder;
  builder.PutPost("pair", params.pair());
  builder.PutPost("qty", params.qty());
  builder.PutPost("quote_qty", params.quote_qty());
  builder.PutPost("side", params.side());
  builder.PutPost("price", params.price());
  builder.PutPost("order_type", params.order_type());
  builder.PutPost("time_in_force", params.time_in_force());
  builder.PutPost("label", params.label());
  builder.PutPost<true>("post_only", params.post_only());
  builder.PutPost<true>("reject_post_only", true);
  builder.PutPost<true>("self_trading_mode", 2);
  auto* context = GetAuth()->CreateRequestByPostWithSignature(endpoint, &builder);

  context->query_type = OrderSubTopicId::SUBMIT_RESPONSE;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BitNativePrivateClient::CancelOrder(const RestParams& params) {
  CHECK_API_LIMIT(ActionType::CANCEL, "/spot/v1/cancel_orders");

  UrlParamsBuilder builder;
  builder.PutPost("order_id", params.order_id());
  builder.PutPost("label", params.label());
  auto* context = GetAuth()->CreateRequestByPostWithSignature(endpoint, &builder);

  context->query_type = OrderSubTopicId::CANCEL_RESPONSE;
  context->extra_info = DebugString();
  return std::shared_ptr<AsioHttpContext>(context);
}

std::shared_ptr<AsioHttpContext> BitNativePrivateClient::PlaceOrderNorm(
    const OrderExecution& order_exe) {
  const auto& order_spec = *order_exe.order_spec;
  const auto proc_order_id = order_exe.proc_order_id;
  auto params = GetRestOrderParams(order_spec, proc_order_id);
  return PlaceOrder(params);
}

std::shared_ptr<AsioHttpContext> BitNativePrivateClient::CancelOrderNorm(
    const OrderExecution& order_exe) {
  auto params = GetRestCancelParams(*order_exe.oc);
  return CancelOrder(params);
}

}  // namespace coin2::exchange::bit::api_order
